﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Mechanical;
using YArchitech.BIM;
using YArchitech.Controls;
using YArchitech.DataModel;
using YArchitech.LIB;
using YArchitech.LIB.YJKControls;
using YArchitech.Revit;

namespace YArchitech.HYSpace
{
	public partial class EditSpaceInfoGrid : System.Windows.Forms.Form
	{
		public EditSpaceInfoGrid(Document document, IList<Space> spaceList)
		{
			this.InitializeComponent();
			base.Icon = Resource.YArchitechIcon;
			EditSpaceInfoGrid.doc = document;
			this.listSpace = spaceList;
			this.listPara = SpaceParameterOperate.GetParameterName();
			this.tvSpaceName.HideSelection = false;
			this.tvSpaceName.DrawMode = TreeViewDrawMode.OwnerDrawText;
			this.tvSpaceName.DrawNode += this.tvSpaceUse_DrawNode;
			EditSpaceInfoGrid.listTAssign = this.loadParam.GetAllTimeInfo();
		}

		private void EditSpaceInfoGrid_Load(object sender, EventArgs e)
		{
			this.listInfo = EditSpaceInfoGrid.InitialSpaceInfo(this.listPara, this.listSpace);
			if (this.listInfo == null)
			{
				YJKMessageBox.Show("没有要编辑的空间参数\n建议用空间创建功能之后\n再用空间编辑功能！", MessageBoxButtons.OK);
				base.Dispose();
				return;
			}
			this.InitialTreeViewInfo(this.tvSpaceName, this.listInfo, 0);
			foreach (HYSpaceInfo hyspaceInfo in this.listInfo)
			{
				if (this.tvSpaceName.SelectedNode.Tag.ToString() == hyspaceInfo.Id)
				{
					this.BandPropertyGrid(hyspaceInfo);
				}
			}
			this.SetGridLeave();
		}

		private void SetGridLeave()
		{
			this.PropertyGridInfo.Leave += this.GridLeave;
		}

		private void GridLeave(object sender, EventArgs e)
		{
			if (base.ActiveControl == this.btnExit)
			{
				return;
			}
			if (!this.isChangeSucceed)
			{
				YJKMessageBox.Show("请输入合适的参数");
				this.PropertyGridInfo.Select();
				return;
			}
		}

		private void BandPropertyGrid(HYSpaceInfo spi)
		{
			PropertyGridMgr propertyGridMgr = new PropertyGridMgr();
			foreach (SpacePara spacePara in spi.Param)
			{
				if (spacePara != null && !(spacePara.Key == "ID") && !(spacePara.Key == "盈建科-夏季空调设计温度(℃)") && !(spacePara.Key == "盈建科-冬季空调设计温度(℃)") && !(spacePara.Key == "盈建科-夏季空调设计相对湿度(%)") && !(spacePara.Key == "盈建科-冬季空调设计相对湿度(%)") && !(spacePara.Key == "盈建科-新风量(m^3/(h.人))"))
				{
					if (spacePara.Key == "盈建科-劳动强度(enum)")
					{
						int num = 0;
						string[] array = new string[]
						{
							"静坐",
							"极轻劳动",
							"轻度劳动",
							"中度劳动",
							"重度劳动"
						};
						if (spacePara.Value != "")
						{
							num = (int)Enum.Parse(typeof(LaborIntensity), spacePara.Value);
						}
						propertyGridMgr.Add(new PropertyGridItem(spacePara.Key, array[num], false, true)
						{
							Category = spacePara.Group,
							Converter = new DropDownListConverter(array)
						});
					}
					else
					{
						if (spacePara.Value == "")
						{
							string key = spacePara.Key;
							if (!(key == "盈建科-人员时间表"))
							{
								if (!(key == "盈建科-新风时间表"))
								{
									if (!(key == "盈建科-照明时间表"))
									{
										if (!(key == "盈建科-电动设备时间表"))
										{
											if (!(key == "盈建科-电子设备时间表"))
											{
												if (key == "盈建科-电热设备时间表")
												{
													spacePara.Value = "电热设备_默认";
												}
											}
											else
											{
												spacePara.Value = "电子设备_默认";
											}
										}
										else
										{
											spacePara.Value = "电动设备_默认";
										}
									}
									else
									{
										spacePara.Value = "照明_默认";
									}
								}
								else
								{
									spacePara.Value = "新风_默认";
								}
							}
							else
							{
								spacePara.Value = "人员_默认";
							}
						}
						PropertyGridItem propertyGridItem = new PropertyGridItem(spacePara.Key, spacePara.Value, false, true);
						propertyGridItem.Category = spacePara.Group;
						if (spacePara.Key.Contains("时间表"))
						{
							propertyGridItem.Editor = new Editor();
						}
						propertyGridMgr.Add(propertyGridItem);
					}
				}
			}
			this.PropertyGridInfo.SelectedObject = propertyGridMgr;
		}

		private void PropertyGridInfo_PropertyValueChanged(object s, PropertyValueChangedEventArgs e)
		{
			this.isChangeSucceed = true;
			foreach (HYSpaceInfo hyspaceInfo in this.listInfo)
			{
				if (!(hyspaceInfo.Id != this.tvSpaceName.SelectedNode.Tag.ToString()))
				{
					foreach (SpacePara spacePara in hyspaceInfo.Param)
					{
						GridItem changedItem = e.ChangedItem;
						if (spacePara.Key == changedItem.Label)
						{
							if (changedItem.Label == "盈建科-劳动强度(enum)")
							{
								int num = 0;
								string a = changedItem.Value.ToString();
								if (!(a == "静坐"))
								{
									if (!(a == "极轻劳动"))
									{
										if (!(a == "轻度劳动"))
										{
											if (!(a == "中度劳动"))
											{
												if (a == "重度劳动")
												{
													num = 4;
												}
											}
											else
											{
												num = 3;
											}
										}
										else
										{
											num = 2;
										}
									}
									else
									{
										num = 1;
									}
								}
								else
								{
									num = 0;
								}
								spacePara.Value = num.ToString();
								break;
							}
							if (spacePara.Key.Contains("时间表"))
							{
								string tsParent = spacePara.Key.Replace("盈建科-", "").Replace("时间表", "");
								if (this.loadParam.IsEffectiveTimeAssignName(tsParent, changedItem.Value.ToString(), EditSpaceInfoGrid.listTAssign))
								{
									spacePara.Value = changedItem.Value.ToString();
									break;
								}
								this.isChangeSucceed = false;
								break;
							}
							else
							{
								try
								{
									double.Parse(changedItem.Value.ToString().Trim());
								}
								catch
								{
									this.isChangeSucceed = false;
								}
								if (spacePara.Key == "盈建科-冬季采暖设计温度(℃)" && this.isChangeSucceed)
								{
									string value = changedItem.Value.ToString();
									double num2 = Convert.ToDouble(value);
									if (num2 < 13.0 || num2 > 113.0)
									{
										this.isChangeSucceed = false;
										break;
									}
									spacePara.Value = value;
									break;
								}
								else if (spacePara.Key.Contains("同时使用系数") && this.isChangeSucceed)
								{
									string value2 = changedItem.Value.ToString();
									double num3 = Convert.ToDouble(value2);
									if (num3 < 0.0 || num3 > 1.0)
									{
										this.isChangeSucceed = false;
										break;
									}
									spacePara.Value = value2;
									break;
								}
								else if (spacePara.Key.Contains("(%)") && this.isChangeSucceed)
								{
									string value3 = changedItem.Value.ToString();
									double num4 = Convert.ToDouble(value3);
									if (num4 < 0.0 || num4 > 100.0)
									{
										this.isChangeSucceed = false;
										break;
									}
									spacePara.Value = value3;
									break;
								}
								else
								{
									if (this.isChangeSucceed)
									{
										spacePara.Value = changedItem.Value.ToString();
										break;
									}
									break;
								}
							}
						}
					}
				}
			}
		}

		public static IList<HYSpaceInfo> InitialSpaceInfo(IList<string> listPara, IList<Space> listSpace)
		{
			string group = "1.设计参数";
			string group2 = "2.冷热指标";
			string group3 = "3.其他参数";
			IList<HYSpaceInfo> list = new List<HYSpaceInfo>();
			foreach (Space space in listSpace)
			{
				HYSpaceInfo hyspaceInfo = new HYSpaceInfo();
				hyspaceInfo.Id = space.Id.ToString();
				hyspaceInfo.Name = space.Name;
				hyspaceInfo.Param = new List<SpacePara>();
				foreach (string text in listPara)
				{
					if (!YJKRevitTools.ShareParaBeExist(space, text))
					{
						return null;
					}
					SpacePara spacePara = new SpacePara();
					Parameter parameter = space.GetParameter(text);
					if (!parameter.HasValue)
					{
						spacePara.Value = "";
					}
					else if (text == "盈建科-劳动强度(enum)" || text.Contains("时间表"))
					{
						spacePara.Value = parameter.AsString();
					}
					else if (text.Contains("湿度"))
					{
						spacePara.Value = (parameter.AsDouble() * 100.0).ToString();
					}
					else if (text.Contains("温度"))
					{
                        spacePara.Value = UnitConvert.CovertFromAPI((DisplayUnitType)57, Convert.ToDouble(parameter.AsDouble())).ToString();
					}
					else
					{
						spacePara.Value = parameter.AsDouble().ToString();
					}
					if (text.Contains("设计"))
					{
						spacePara.Group = group;
					}
					else if (text.Contains("指标"))
					{
						spacePara.Group = group2;
					}
					else
					{
						spacePara.Group = group3;
					}
					spacePara.Key = text;
					hyspaceInfo.Param.Add(spacePara);
				}
				list.Add(hyspaceInfo);
			}
			return list;
		}

		public void InitialTreeViewInfo(TreeView tv, IList<HYSpaceInfo> listSpaceInfo, int selIndex)
		{
			foreach (HYSpaceInfo hyspaceInfo in listSpaceInfo)
			{
				TreeNode treeNode = new TreeNode();
				treeNode.Text = hyspaceInfo.Name;
				treeNode.Tag = hyspaceInfo.Id;
				tv.Nodes.Add(treeNode);
			}
			this.tvSpaceName.SelectedNode = this.tvSpaceName.Nodes[selIndex];
		}

		private void tvSpaceName_AfterSelect(object sender, TreeViewEventArgs e)
		{
			this.isTreeChange = true;
			foreach (HYSpaceInfo hyspaceInfo in this.listInfo)
			{
				if (this.tvSpaceName.SelectedNode.Tag.ToString() == hyspaceInfo.Id)
				{
					this.BandPropertyGrid(hyspaceInfo);
				}
			}
		}

		private void tvSpaceUse_DrawNode(object sender, DrawTreeNodeEventArgs e)
		{
			e.DrawDefault = true;
			if ((e.State & TreeNodeStates.Selected) != (TreeNodeStates)0)
			{
				e.Graphics.FillRectangle(Brushes.DarkBlue, e.Node.Bounds);
				Font font = e.Node.NodeFont;
				if (font == null)
				{
					font = ((TreeView)sender).Font;
				}
				e.Graphics.DrawString(e.Node.Text, font, Brushes.White, Rectangle.Inflate(e.Bounds, 2, 0));
			}
			else
			{
				e.DrawDefault = true;
			}
			if ((e.State & TreeNodeStates.Focused) != (TreeNodeStates)0)
			{
                using (Pen pen = new Pen(System.Drawing.Color.Black))
				{
					pen.DashStyle = DashStyle.Dot;
					Rectangle bounds = e.Node.Bounds;
					bounds.Size = new Size(bounds.Width - 1, bounds.Height - 1);
					e.Graphics.DrawRectangle(pen, bounds);
				}
			}
		}

		private void btnSure_Click(object sender, EventArgs e)
		{
			Transaction transaction = new Transaction(EditSpaceInfoGrid.doc, "修改空间参数");
			transaction.Start();
			int num = 0;
			foreach (HYSpaceInfo hyspaceInfo in this.listInfo)
			{
				ElementId elementId = new ElementId(Convert.ToInt32(hyspaceInfo.Id));
				Element element = EditSpaceInfoGrid.doc.GetElement(elementId);
				this.SetRevitSpaceParam(element as Space, hyspaceInfo);
				IList<bool> list = new List<bool>();
				foreach (SpacePara spacePara in hyspaceInfo.Param)
				{
					Parameter parameter = element.GetParameter(spacePara.Key);
					if (!(spacePara.Value == ""))
					{
						if (spacePara.Key.Contains("时间表"))
						{
							list.Add(parameter.Set(spacePara.Value));
						}
						else if (spacePara.Key.Contains("湿度"))
						{
							list.Add(parameter.Set(Convert.ToDouble(spacePara.Value) / 100.0));
						}
						else if (spacePara.Key.Contains("温度"))
						{
							list.Add(parameter.Set(UnitConvert.CovertToAPI(Convert.ToDouble(spacePara.Value), (Autodesk.Revit.DB.DisplayUnitType)57)));
						}
						else if (spacePara.Key.Equals("盈建科-劳动强度(enum)"))
						{
							list.Add(parameter.Set(spacePara.Value));
						}
						else
						{
							list.Add(parameter.Set(Convert.ToDouble(spacePara.Value)));
						}
					}
				}
				IEnumerator<bool> enumerator3 = list.GetEnumerator();
				{
					while (enumerator3.MoveNext())
					{
						if (!enumerator3.Current)
						{
							num++;
						}
					}
				}
			}
			if (num == 0)
			{
				YJKMessageBox.Show("修改成功！");
				this.RemoveEmptyZone();
			}
			transaction.Commit();
			base.Close();
		}

		private void RemoveEmptyZone()
		{
			foreach (Element element in ((IEnumerable<Element>)YJKElementFilter.GetElementByCategory(EditSpaceInfoGrid.doc, BuiltInCategory.OST_HVAC_Zones)))
			{
				Zone zone = element as Zone;
				if (!(zone.Name == "默认") && zone != null && zone.Spaces.IsEmpty)
				{
					EditSpaceInfoGrid.doc.Delete(zone.Id);
				}
			}
		}

		private static void SetZoneParameter(double xjSJWD, double xjXDSD, double djXDSD, double freshAir, double djCNWD, Element elem)
		{
			ZoneInfoManager zoneInfoManager = new ZoneInfoManager(EditSpaceInfoGrid.doc);
			Zone zone = zoneInfoManager.BeExsitZone(xjSJWD, djCNWD, xjXDSD, djXDSD, freshAir);
			Space space = elem as Space;
			SpaceSet spaceSet = new SpaceSet();
			if (zone == null)
			{
				zone = zoneInfoManager.CreatHYZone(EditSpaceInfoGrid.doc, "");
				zoneInfoManager.SetZonePara(zone, xjSJWD, djCNWD, xjXDSD, djXDSD, freshAir);
				spaceSet.Insert(space);
				zone.AddSpaces(spaceSet);
				return;
			}
			zoneInfoManager.SetZonePara(zone, xjSJWD, djCNWD, xjXDSD, djXDSD, freshAir);
			spaceSet.Insert(space);
			if (zone.Id != space.Zone.Id)
			{
				zone.AddSpaces(spaceSet);
			}
		}

		public void SetRevitSpaceParam(Space space, HYSpaceInfo hySpace)
		{
            double num = UnitConvert.CovertFromAPI((DisplayUnitType)12, space.Area);
			foreach (SpacePara spacePara in hySpace.Param)
			{
				if (spacePara.Value == "")
				{
					break;
				}
				string key = spacePara.Key;
				if (!(key == "盈建科-总冷指标(W/m^2)"))
				{
					if (!(key == "盈建科-总热指标(W/m^2)"))
					{
						if (key == "盈建科-人员密度(人/m^2)")
						{
                            space.OccupancyUnit = (OccupancyUnit)1;
							double num2 = 1.0 / Convert.ToDouble(spacePara.Value);
							if (num2 > 0.135 && num2 < 929.03)
							{
								space.AreaperPerson = UnitConvert.CovertToAPI(Convert.ToDouble(num2), (Autodesk.Revit.DB.DisplayUnitType)12);
							}
						}
					}
					else
					{
						Parameter parameter = space.GetParameter(BuiltInParameter.ROOM_DESIGN_HEATING_LOAD_PARAM);
						double num3 = UnitConvert.CovertToAPI(Convert.ToDouble(spacePara.Value), (Autodesk.Revit.DB.DisplayUnitType)40);
						parameter.Set(num3 * num / 1000.0);
					}
				}
				else
				{
					Parameter parameter2 = space.GetParameter(BuiltInParameter.ROOM_DESIGN_COOLING_LOAD_PARAM);
					double num4 = UnitConvert.CovertToAPI(Convert.ToDouble(spacePara.Value), (Autodesk.Revit.DB.DisplayUnitType)40);
					parameter2.Set(num4 * num / 1000.0);
				}
			}
		}

		private void btnExit_Click(object sender, EventArgs e)
		{
			base.Close();
		}

		private void butImport_Click(object sender, EventArgs e)
		{
			FrmShowInfoGrid frmShowInfoGrid = new FrmShowInfoGrid();
			bool flag = false;
			if (frmShowInfoGrid.ShowDialog() == DialogResult.OK)
			{
				new List<SpacePara>();
				foreach (SpaceParameterInfo spaceParameterInfo in FrmShowInfoGrid.listSPI)
				{
					if (frmShowInfoGrid.tvSpaceClass.SelectedNode.Tag.ToString() == spaceParameterInfo.RoomId.ToString())
					{
						foreach (HYSpaceInfo hyspaceInfo in this.listInfo)
						{
							if (this.tvSpaceName.SelectedNode.Tag.ToString() == hyspaceInfo.Id)
							{
								spaceParameterInfo.Param.RemoveAt(42);
								hyspaceInfo.Param = spaceParameterInfo.Param;
								this.BandPropertyGrid(hyspaceInfo);
								flag = true;
								break;
							}
						}
					}
					if (flag)
					{
						break;
					}
				}
			}
		}

		private void PropertyGridInfo_SelectedGridItemChanged(object sender, SelectedGridItemChangedEventArgs e)
		{
			if (!this.isChangeSucceed)
			{
				this.isChangeSucceed = true;
				this.PropertyGridInfo.SelectedGridItem = e.OldSelection;
				if (this.PropertyGridInfo.SelectedGridItem.Label.Contains("时间表"))
				{
					YJKMessageBox.Show("请输入有效的时间指派名称!");
				}
				else if (this.PropertyGridInfo.SelectedGridItem.Label == "盈建科-冬季采暖设计温度(℃)")
				{
					YJKMessageBox.Show("设计温度应该在13-113间");
				}
				else if (this.PropertyGridInfo.SelectedGridItem.Label.Contains("同时使用系数"))
				{
					YJKMessageBox.Show("同时使用系数应该在0-1间");
				}
				else if (this.PropertyGridInfo.SelectedGridItem.Label.Contains("(%)"))
				{
					YJKMessageBox.Show("请输入0-100之间的数值");
				}
				else
				{
					YJKMessageBox.Show("请输入数字!");
				}
				this.isChangeSucceed = false;
			}
		}

		private static Document doc = null;

		private IList<Space> listSpace = new List<Space>();

		private IList<string> listPara = new List<string>();

		public IList<HYSpaceInfo> listInfo = new List<HYSpaceInfo>();

		public static IList<TimeAssign> listTAssign = new List<TimeAssign>();

		private bool isTreeChange;

		private bool isChangeSucceed = true;

		private LoadParamOperate loadParam = new LoadParamOperate();
	}
}
